﻿Public Class PortSwitch
    Implements I_HardwareDataExchange
    Private m_Port As I_HardwareDataExchange
    Private m_IsOpen As Boolean = False
    Public Event PortRequired(ByVal RequireStatus As Boolean)
    Private m_PortReq As Boolean
    Public Property Port() As I_HardwareDataExchange
        Get
            Return m_Port
        End Get
        Set(ByVal value As I_HardwareDataExchange)
            m_Port = value
        End Set
    End Property
    Public ReadOnly Property BytesToRead() As Integer Implements I_HardwareDataExchange.BytesToRead
        Get
            If m_IsOpen Then
                Return m_Port.BytesToRead
            Else
                Return 0
            End If
        End Get
    End Property

    Public ReadOnly Property BytesToWrite() As Integer Implements I_HardwareDataExchange.BytesToWrite
        Get
            If m_IsOpen Then
                Return m_Port.BytesToWrite
            Else
                Return 0
            End If
        End Get
    End Property

    Public Sub ClearBuffers() Implements I_HardwareDataExchange.ClearBuffers
        If m_Port.IsOpen = True And m_IsOpen = True Then
            m_Port.ClearBuffers()
        End If
    End Sub

    Public Sub ClosePort() Implements I_HardwareDataExchange.ClosePort
        m_IsOpen = False
    End Sub
    Public Function Read() As Byte() Implements I_HardwareDataExchange.Read
        If m_Port.IsOpen And m_IsOpen Then
            Return m_Port.Read
        End If
        Return Nothing
    End Function
    Public Function Read(ByVal Count As Integer) As Byte() Implements I_HardwareDataExchange.Read
        If m_Port.IsOpen And m_IsOpen Then
            Return m_Port.Read(Count)
        End If
        Return Nothing
    End Function
    Public Sub Write(ByVal data() As Byte) Implements I_HardwareDataExchange.Write
        If m_Port.IsOpen And m_IsOpen Then
            m_Port.Write(data)
        End If
    End Sub
    Public ReadOnly Property IsOpen() As Boolean Implements I_HardwareDataExchange.IsOpen
        Get
            Return m_IsOpen
        End Get
    End Property
    Public Sub OpenPort() Implements I_HardwareDataExchange.OpenPort
        m_PortReq = True
        RaiseEvent PortRequired(m_PortReq)
    End Sub
    Public Sub ConnectPorts()
        m_Port.OpenPort()
        Dim s As Long = My.Computer.Clock.TickCount
        Do
            If My.Computer.Clock.TickCount > s + 2000 Then
                m_IsOpen = False
                m_PortReq = False
                Exit Sub
            End If
        Loop Until m_Port.IsOpen
        m_PortReq = False
        m_IsOpen = True
        RaiseEvent PortRequired(m_PortReq)
    End Sub
End Class
